#pragma GCC optimize(2)
#include <bits/stdc++.h>

using namespace std;
#define int long long
const int inf = 0x3f3f3f3f3f3f3f3f;

vector<int> p;

int qpow(int a, int b)
{
    int ret = 1;
    while (b > 0)
    {
        if (b & 1)
            ret = ret * a;
        a = a * a;
        b >>= 1;
    }
    return ret;
}

void solve()
{
    int n;
    cin >> n;
    int ans = 0;
    while (n != 0)
    {
        int pos = lower_bound(p.begin(), p.end(), n) - p.begin();
        if (p[pos] != n) pos--;
        n -= p[pos];
        ans += qpow(3, pos + 1) + pos * qpow(3, pos - 1);
    }
    cout << ans << '\n';
}

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int x = 1;
    p.push_back(x);
    while (x <= 1e9)
    {
        x *= 3;
        p.push_back(x);
    }
    int _ = 1;
    cin >> _;
    while (_--)
    {
        solve();
    }
    return 0;
}